package com.nandi.emergencyinspection.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.blankj.utilcode.util.BarUtils
import com.bumptech.glide.Glide

import com.luck.picture.lib.tools.ToastUtils
import com.nandi.emergencyinspection.R
import com.nandi.emergencyinspection.bean.UserInfoBean
import com.nandi.emergencyinspection.customconfig.mBaseUrl
import com.nandi.emergencyinspection.mvp.LoginContract
import com.nandi.emergencyinspection.mvp.LoginPresenter
import com.nandi.emergencyinspection.ui.activity.macro.MacroActivity
import com.nandi.emergencyinspection.ui.activity.macro.MainMacroActivity
import com.nandi.emergencyinspection.utils.AESUtil
import com.nandi.emergencyinspection.utils.Random
import com.nandi.emergencyinspection.utils.SxPermissionsTool
import com.orhanobut.hawk.Hawk
import com.tbright.ktbaselibrary.mvp.BaseMvpActivity
import io.rong.callkit.RongCallKit
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import kotlinx.android.synthetic.main.activity_login.*


class LoginActivity : BaseMvpActivity<LoginPresenter>(), LoginContract.LoginView {
    private var randomNum = Random.randomLenNum()
    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initView(savedInstanceState: Bundle?) {
        SxPermissionsTool.with(this)
            .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .addPermission(Manifest.permission.CAMERA)
            .addPermission(Manifest.permission.RECORD_AUDIO)
            .initPermission()
//        setStatusBarColor(R.color.black)
        BarUtils.setStatusBarVisibility(this, false)
        login.setOnClickListener {
            if (verification()) {
                mPresenter?.login("", getVCode(), randomNum, getUserName(), getPwd())
                vcode.setText("")
                getRaRandom()
            } else {
                ToastUtils.s(this, "请检查填写的信息")
            }
        }
        val s = "${mBaseUrl}code?randomStr=$randomNum"
        Glide.with(this).load(s).into(yzmImg)
        yzmImg.setOnClickListener {
            getRaRandom()
        }
    }

    private fun verification(): Boolean {
        return getPwd().isNotEmpty() && getUserName().isNotEmpty() && getVCode().isNotEmpty()
    }

    private fun getRaRandom() {
        vcode.setText("")
        randomNum = Random.randomLenNum()
        Glide.with(this)
            .load("${mBaseUrl}code?randomStr=$randomNum")
            .into(yzmImg)
    }

    private fun getUserName(): String {
        return user.text.toString().trim()
    }

    private fun getPwd(): String {
        return AESUtil.encrypt(pwd.text.toString().trim(), "_CQNDT_LH_CLOUD_")
    }

    private fun getVCode(): String {
        return vcode.text.toString().trim()
    }

    override fun loginResult(result: String) {
        val s = result.split(";")[0]
        Hawk.put("TOKEN", s)
        mPresenter?.getUser(result.split(";")[1])

    }

    override fun getIm(result: String) {
//        val fromJson = Gson().fromJson(result, Bean::class.java) as Bean
//        connectIM(fromJson.token)
        connectIM(result)
    }

    override fun getUserResult(result: UserInfoBean) {
        Hawk.put("USER", result)
        mPresenter?.getIm(result.realname.toString(), result.phone.toString())
    }

    private fun connectIM(token: String) {

        RongIM.connect(token, object : RongIMClient.ConnectCallback() {
            @SuppressLint("ResourceAsColor")
            override fun onSuccess(p0: String?) {
//                Toast.makeText(this@MainActivity, "登录成功，请不要重复登录", Toast.LENGTH_SHORT).show()
                RongCallKit.onViewCreated()
                val intent = Intent(applicationContext, MainMacroActivity::class.java)
                startActivity(intent)
                finish()
            }

            override fun onDatabaseOpened(p0: RongIMClient.DatabaseOpenStatus?) {

            }

            override fun onError(p0: RongIMClient.ConnectionErrorCode?) {
                getRaRandom()
                RongIM.getInstance().logout()
                ToastUtils.s(this@LoginActivity, "视频组件初始化失败，重新打开APP")
            }

        })
    }
}